package com.hzncc.flowable_diboot.controller.report;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.diboot.core.util.V;
import com.diboot.core.util.S;
import com.diboot.core.util.ContextHolder;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.LabelValue;
import com.diboot.core.vo.Pagination;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.iam.entity.SystemConfig;
import com.diboot.iam.service.SystemConfigService;
import com.diboot.iam.util.IamSecurityUtils;
import com.diboot.tenant.service.IamTenantService;
import com.hzncc.flowable_diboot.util.ConstantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.hzncc.flowable_diboot.entity.report.WeeklySummaryReport;
import com.hzncc.flowable_diboot.service.report.WeeklySummaryReportService;
import com.hzncc.flowable_diboot.vo.report.WeeklySummaryReportDetailVO;
import com.hzncc.flowable_diboot.vo.report.WeeklySummaryReportListVO;
import com.hzncc.flowable_diboot.dto.report.WeeklySummaryReportDTO;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 周报报表 相关rest接口
 *
 * @author MyName
 * @version 1.0
 * @date 2024-11-25
 * Copyright © MyCorp
 */
@Slf4j
@RequestMapping("/report/weekly-summary-report")
@BindPermission(name = "周报报表")
@RestController
public class WeeklySummaryReportController extends BaseCrudRestController<WeeklySummaryReport> {

    @Autowired
    private WeeklySummaryReportService weeklySummaryReportService;

    @Autowired
    private IamTenantService iamTenantService;

    @Autowired
    private SystemConfigService systemConfigService;

    /**
     * 查询资源对象的列表VO记录
     * <p>
     * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<WeeklySummaryReportListVO>> getListVOMapping(WeeklySummaryReportDTO queryDto, Pagination pagination) throws Exception {
        return super.getViewObjectList(queryDto, pagination, WeeklySummaryReportListVO.class);
    }

    /**
     * 根据id查询资源对象的详情VO
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<WeeklySummaryReportDetailVO> getDetailVOMapping(@PathVariable("id") String id) throws Exception {
        WeeklySummaryReportDetailVO detailVO = weeklySummaryReportService.getViewObject(id, WeeklySummaryReportDetailVO.class);
        return JsonResult.OK(detailVO);
    }

    /**
     * 根据指定字段和值查询资源对象的详情VO
     *
     * @param fieldName  字段名
     * @param fieldValue 字段值
     * @return
     * @throws Exception
     */
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{fieldName}/{fieldValue}")
    public JsonResult<WeeklySummaryReportDetailVO> getDetailVOMapping(@PathVariable("fieldName") String fieldName, @PathVariable("fieldValue") String fieldValue) throws Exception {
        WeeklySummaryReportDetailVO detailVO = weeklySummaryReportService.getViewObject(fieldName, fieldValue, WeeklySummaryReportDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
     * 创建资源对象数据
     *
     * @param weeklySummaryReport
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<Serializable> createModelMapping(@RequestBody WeeklySummaryReport weeklySummaryReport) throws Exception {
        weeklySummaryReport.setWeek(LocalDateTimeUtil.weekOfYear(LocalDateTimeUtil.now()));
        weeklySummaryReport.setMondayDate(LocalDateTimeUtil.of(DateUtil.beginOfWeek(new Date())).toLocalDate());
        weeklySummaryReport.setEditMembers(IamSecurityUtils.getCurrentUserId());
        weeklySummaryReport.setTenantName(iamTenantService.getEntity(IamSecurityUtils.getCurrentTenantId()).getName());
        weeklySummaryReportService.createEntity(weeklySummaryReport);
        return JsonResult.OK(weeklySummaryReport.getId());
    }

    /**
     * 根据id更新资源对象
     *
     * @param weeklySummaryReport
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id") String id, @RequestBody WeeklySummaryReport weeklySummaryReport) throws Exception {
        String editMembers = weeklySummaryReport.getEditMembers();
        if (!S.contains(editMembers, IamSecurityUtils.getCurrentUserId())) {
            weeklySummaryReport.setEditMembers(editMembers + "," + IamSecurityUtils.getCurrentUserId());
        }
        weeklySummaryReportService.updateEntity(weeklySummaryReport);
        return JsonResult.OK();
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = weeklySummaryReportService.deleteEntity(id);
        log.debug("删除数据 周报报表:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK();
    }

    /**
     * 根据ids集合删除资源对象
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = weeklySummaryReportService.deleteEntities(ids);
        log.debug("批量删除数据 周报报表:{} {}", ids, success ? "成功" : "失败");
        return JsonResult.OK();
    }

    @GetMapping("/test")
    public JsonResult<?> getWeeklyReport() throws Exception {
        weeklySummaryReportService.sendWeeklyReportFile(null);
        return JsonResult.OK();
    }


    /**
     * 修改周报接收人
     * @param userNums
     * @return
     */
    @PostMapping("/modifyRecipient/{userNums}")
    public JsonResult<?> modifyRecipient(@PathVariable String userNums){
        UpdateWrapper<SystemConfig> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(SystemConfig::getPropValue, userNums).eq(SystemConfig::getPropKey, ConstantUtil.WEEKLY_REPORT_RECIPIENT);
        boolean b = systemConfigService.updateEntity(updateWrapper);
        return JsonResult.OK(b);
    }

    /**
     * 获取周报接收人
     * @return
     */
    @GetMapping("/getRecipient")
    public JsonResult<?> getRecipient(){
        QueryWrapper<SystemConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SystemConfig::getPropKey, ConstantUtil.WEEKLY_REPORT_RECIPIENT);
        SystemConfig systemConfig = systemConfigService.getSingleEntity(queryWrapper);
        return JsonResult.OK(systemConfig.getPropValue());
    }

}